package com.ks.phone.manager;

import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import com.ks.basictools.ActivityManager;
import com.ks.basictools.utils.ToastUtils;
import com.ks.phone.UserManager;
import com.ks.phone.constant.Constants;
import com.ks.phone.provider.ContextGlobal;
import com.ks.phone.responseBean.PhoneResponse;
import com.ks.phone.responseBean.SaveCallInfoResponse;
import com.ks.phone.responseBean.UserResponse;
import com.ks.phone.utils.FileUtils;
import com.ks.phone.view.MainActivity;
import com.ks.phone.wedget.PopupTip;
import com.xuexiang.xhttp2.XHttp;
import com.xuexiang.xhttp2.callback.SimpleCallBack;
import com.xuexiang.xhttp2.callback.UIProgressResponseCallBack;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xhttp2.subsciber.ProgressLoadingSubscriber;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

public class CallPhoneManager {

    private Timer mTimer;
    private PopupTip popupTip;

    private static class CallPhoneManagerHolder {
        private static final CallPhoneManager instance = new CallPhoneManager();
    }

    public CallPhoneManager() {
    }

    public static CallPhoneManager getInstance() {
        return CallPhoneManagerHolder.instance;
    }

    public void requestHttpGetPhone() {
        String token = PreferenceManager.getInstance().getToken(ContextGlobal.get().getContext());
        if (TextUtils.isEmpty(token)) {
            return;
        }
        UserResponse.UserDTO user = UserManager.getInstance().getUser();
        Map<String, Object> param = new HashMap<>();
        param.put("userid", user.getId());
        param.put("token", token);
        XHttp.post(Constants.URL_CALL)
                .params(param)
                .execute(new SimpleCallBack<PhoneResponse>() {
                    @Override
                    public void onSuccess(PhoneResponse info) {
                        Log.d("zhxk", "onSuccess: info = " + info);
                        if (!TextUtils.isEmpty(info.getPhone())) {
                            stopTimer();
                            callPhone(info.getPhone());
                        }
                    }

                    @Override
                    public void onError(ApiException e) {
                    }
                });
    }


    public void requestHttpSaveCallInfo() {
        String token = PreferenceManager.getInstance().getToken(ContextGlobal.get().getContext());
        if (TextUtils.isEmpty(token)) {
            return;
        }
//        String recordPath = FileUtils.getRecordPath();
        String recordPath = PreferenceManager.getInstance().getRecordPath(ContextGlobal.get().getContext());
        String replace = recordPath.replace("/内置SD卡", Environment.getExternalStorageDirectory()
                .getAbsolutePath());
        Log.d("zhxk", "requestHttpSaveCallInfo: recordPath = " + replace);
        File targetFile = FileUtils.searchFiles(new File(replace), Constants.phone);
        if (targetFile != null) {
            Log.d("zhxk", "录音文件: " + targetFile.getAbsolutePath());
        } else {
            if (FileUtils.isConnected.get()) {
                // 电话已接通，但没有找到录音文件
                ToastUtils.show(ContextGlobal.get().getContext(), "没有找到录音文件");
                Log.e("zhxk", "没有找到目标录音文件");
                if (popupTip == null) {
                    popupTip = new PopupTip(ContextGlobal.get().getContext());
                    popupTip.setContent("没有找到录音文件，请点击右上角「设置」检查路径是否填写正确");
                    popupTip.setOnConfirmClickListener(v -> popupTip.dismiss());
                }
                if (!popupTip.isShowing()) {
                    popupTip.showPopupWindow();
                }
            }
            // 电话未接通，直接返回
            return;
        }
        String second = String.valueOf(FileUtils.getMp3Duration(targetFile) / 1000);
        Log.d("zhxk", "录音时长: " + second);

        UserResponse.UserDTO user = UserManager.getInstance().getUser();
        Map<String, Object> param = new HashMap<>();
        param.put("token", token);
        param.put("userid", user.getId());
        param.put("phone", Constants.phone);
        param.put("status", "1");
        param.put("second", second);
        XHttp.post(Constants.URL_CALL_INFO_SAVE)
                .params(param)
                .uploadFile("file", targetFile, new UIProgressResponseCallBack() {
                    @Override
                    public void onUIResponseProgress(long bytesRead, long contentLength, boolean done) {
                        Log.d("zhxk", "录音文件上传进度: bytesRead = " + bytesRead
                                + " contentLength = " + contentLength
                                + "  done = " + done);
                    }
                })
                .execute(SaveCallInfoResponse.class)
                .subscribeWith(new ProgressLoadingSubscriber<SaveCallInfoResponse>() {
                    @Override
                    protected void onSuccess(SaveCallInfoResponse respond) {
                        ToastUtils.show(ContextGlobal.get().getContext(), "录音文件上传成功");
                    }
                });
    }


    public void startTimer() {
        stopTimer();
        mTimer = new Timer();
        TimerTask mTimerTask = new TimerTask() {
            @Override
            public void run() {
                // 在这里编写定时执行的任务逻辑
                // 例如更新UI、发送网络请求等操作
                requestHttpGetPhone();
            }
        };
        // 使用schedule方法安排任务的执行
        // 第一个参数是TimerTask对象，表示要执行的任务
        // 第二个参数是延迟执行的时间，单位是毫秒
        // 第三个参数是任务执行的间隔时间，单位也是毫秒
        mTimer.schedule(mTimerTask, 5000, 5000);
    }

    public void stopTimer() {
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
    }

    private void callPhone(String phone) {
//        phone = "10000";
        Constants.phone = phone;
        // 调用系统拨号界面
        Intent callIntent = new Intent(Intent.ACTION_CALL);
        callIntent.setData(Uri.parse("tel:" + phone));
        ActivityManager.getInstance().getActivity(MainActivity.class).startActivity(callIntent);
    }
}
